package com.spc.redis.serializer;

import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import static com.spc.redis.serializer.SerializerUtil.isPrimitiveOrString;


/**
 * hutool-json 实现
 *
 * @author alex
 * @version v1.0 2021/3/17
 */
public class HutoolJsonSerializer extends AbstractSerializer {

    public static final String TYPE = "hutool";

    private static final JSONConfig JSON_CONFIG;

    static {
        JSON_CONFIG = JSONConfig.create();
    }

    /**
     * 序列化一个对象到 字符串
     *
     * @param obj
     * @return
     */
    @Override
    public <T> String serialize(T obj) throws SerializeException {
        try {
            if (isPrimitiveOrString(obj)) {
                return String.valueOf(obj);
            }
            return JSONUtil.toJsonStr(obj);
        } catch (Exception e) {
            throw new SerializeException(e);
        }
    }

    /**
     * 反序列化到对象
     * TODO:
     * 考虑基本数据类型
     *
     * @param value
     * @param clazz
     * @return
     */
    @Override
    public <T> T deserialize(String value, Class<T> clazz) throws SerializeException {
        if (isPrimitiveOrString(clazz)) {
            return toPrimitiveValue(value, clazz);
        }
        JSONObject jsonObject = JSONUtil.parseObj(value, JSON_CONFIG);
        if (jsonObject == null) {
            throw new SerializeException("parse result is null");
        }
        return JSONUtil.toBean(jsonObject, clazz);
    }
}
